package cn.wolfcode.web.advice;

import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.web.exection.BussionExction;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(BussionExction.class)
    public void bussionExction(BussionExction e, HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation != null){
            response.setContentType("application/json;charset=utf-8");

            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg(e.getMessage());
            response.getWriter().write(JSON.toJSONString(jsonResult));
        }else {
            response.sendRedirect("/employee/error");
        }
    }

    @ExceptionHandler(Exception.class)
    public void sessionHanle(Exception e, HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation != null){
            response.setContentType("application/json;charset=utf-8");

            JsonResult jsonResult = new JsonResult();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("系统异常");
            response.getWriter().write(JSON.toJSONString(jsonResult));
        }else {
            response.sendRedirect("/employee/error");
        }
    }

}
